package controllers

import (
	"MaternalBaby/api/models"
	"time"

	"github.com/astaxie/beego"
	"github.com/oldfeel/ofutils"
)

type Record struct {
	BaseController
}

// @router /add [get]
func (c *Record) Add() {
	var m models.Record
	err := c.ParseForm(&m)
	if err != nil {
		c.Fail(1, err)
		return
	}

	beego.Info("record is ", ofutils.ToJson(m))
	if m.Id == 0 {
		m.CreatorId = c.u.Id
		m.CreateTime = time.Now()
		_, err = o.Insert(&m)
		if err != nil {
			c.Fail(2, err)
			return
		}
	} else {
		_, err = o.Update(&m, "RType", "RecordTime", "Remark")
		if err != nil {
			c.Fail(3, err)
			return
		}
	}
	c.Success(m)
}

// @router /info [get]
func (c *Record) Info() {
	id, _ := c.GetInt("id")
	var m models.Record
	o.QueryTable(m).Filter("Id", id).One(&m)
	c.Success(m)
}

// @router /remarkHistory [get]
func (c *Record) RemarkHistory() {
	pId, _ := c.GetInt("pId")
	rType := c.GetString("rType")
	var remarks []string
	o.Raw("select remark from record where p_id=? and r_type=? group by remark order by max(create_time) desc limit 10", pId, rType).QueryRows(&remarks)
	c.Success(remarks)
}

// @router /delete [get]
func (c *Record) Delete() {
	id, _ := c.GetInt("id")
	_, err := o.Delete(&models.Record{Id: id})
	if err != nil {
		c.Fail(1, err)
		return
	}
	c.Success("")
}

// @router /list [get]
func (c *Record) List() {
	id, _ := c.GetInt("id")

	var list []models.Record
	o.QueryTable("Record").Filter("PId", id).OrderBy("-RecordTime").All(&list)

	c.Success(list)
}
